/**
 *
 */
package com.jing.weibo.scheduler.task;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.pojo.Fansattention;
import com.jing.weibo.pojo.Synchrolog;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.service.user.SynchrologService;
import com.jing.weibo.ws.sina.SinaService;

/**
 * 定时任务类
 * @author jing.yue
 * @version 2012/09/18 1.0.0
 */
@Component
public class Task extends TaskAbs {

	private static final Logger logger = Logger.getLogger(Task.class);

	@Autowired
	private SynchrologService synchrologService;

	@Autowired
	private SinaService sinaService;

	@Autowired
	private FansAttentionService fansAttentionService;

	/**
	 * 获取数据的定时任务类
	 * @param username 用户名
	 * @param token
	 * @param fansAttentionType 同步类型
	 */
	@Override
	public void loadUsernameData(String username, String token, FansAttentionType fansAttentionType) {
		// TODO Auto-generated method stub
		try {
			//判断是否同步过
			Synchrolog synchrolog = new Synchrolog();
			synchrolog.setUsername(username);
			synchrolog.setSynchrotable(fansAttentionType.getCode());
			Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);
			Date querytime = DateUtils.addMinutes(Calendar.getInstance().getTime(), WeiboCons.UPDATE_PAST_DUE_DATE);
			if(sl == null) {
				synchroFansAttention(username, token, fansAttentionType);
				//添加用户同步记录
				synchrologService.saveSynchrolog(synchrolog);
			}
			//有数据, 但距离上传更新数据超过15分钟
			else if(sl != null && sl.getSynchrotime().compareTo(querytime) == -1) {
				synchroFansAttention(username, token, fansAttentionType);
				//根据用户名和同步的表名修改用户同步记录信息
				synchrologService.updateSynchrolog(sl);
			}
		} catch (WeiboException e) {
			logger.error(username + ": 调用微博接口获取数据[类型: " + fansAttentionType.getText() + "]异常: " + WeiboCons.getErrorMsg(e), e);
		} catch (Exception e) {
			logger.error(username + ": 获取数据[类型: " + fansAttentionType.getText() + "]异常", e);
		}
	}

	/**
	 * 同步粉丝信息
	 * @param username
	 * @param token
	 * @param fansAttentionType
	 * @throws WeiboException, Exception
	 */
	private void synchroFansAttention(String username, String token, FansAttentionType fansAttentionType) throws WeiboException, Exception {
		Fansattention fansattention = null;
		switch (fansAttentionType) {
		case TYPE_ATTENTION:

			//获取所有关注
			/*int friendsSize = 0;
			List<UserWapper> friendsList = sinaService.getFriendsByIDAll(username, token);*/

			//根据用户和类型删除历史记录
			fansattention = new Fansattention();
			fansattention.setUsername(username);
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);

			UserWapper userWapper = sinaService.getFriendsByID(username, WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, 0, token);
			saveFansattention(username, fansAttentionType, fansattention, userWapper);
			if(userWapper.getNextCursor() > 0l) {
				while(true) {
					//休眠2s
					Thread.sleep(SystemCons.THREAD_QUERY_SLEEP_DATE);

					userWapper = sinaService.getFriendsByID(username, WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, Long.valueOf(userWapper.getNextCursor()).intValue(), token);
					//不存在数据
					if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
						break;
					}
					//不存在下一页
					else if(userWapper.getNextCursor() <= 0l) {
						saveFansattention(username, fansAttentionType, fansattention, userWapper);
						break;
					}
					else {
						saveFansattention(username, fansAttentionType, fansattention, userWapper);
					}
				}
			}

			/*for (UserWapper userWapper : friendsList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = BaseController.setFansattention(user, username, fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				friendsSize += userWapper.getUsers().size();
			}
			logger.info("[" + username + "]关注为: " + friendsSize);*/
			break;
		case TYPE_FANS:

			//获取所有粉丝
			//int fansSize = 0;
			//List<UserWapper> fansList = sinaService.getFollowersByIdAll(username, token);

			//根据用户和类型删除历史记录
			fansattention = new Fansattention();
			fansattention.setUsername(username);
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);

			userWapper = sinaService.getFollowersById(username, WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, 0, token);
			saveFansattention(username, fansAttentionType, fansattention, userWapper);

			if(userWapper.getNextCursor() > 0l) {
				while(true) {
					//休眠2s
					Thread.sleep(SystemCons.THREAD_QUERY_SLEEP_DATE);

					userWapper = sinaService.getFollowersById(username, WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, Long.valueOf(userWapper.getNextCursor()).intValue(), token);
					//不存在数据
					if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
						break;
					}
					//不存在下一页
					else if(userWapper.getNextCursor() <= 0l) {
						saveFansattention(username, fansAttentionType, fansattention, userWapper);
						break;
					}
					else {
						saveFansattention(username, fansAttentionType, fansattention, userWapper);
					}
				}
			}


			/*for (UserWapper userWapper : fansList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = BaseController.setFansattention(user, username, fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				//fansSize += userWapper.getUsers().size();
			}*/
			//logger.info("[" + username + "]粉丝为: " + fansSize);
			break;
		default:
			break;
		}
	}

	/**
	 * 保存信息
	 * @param username
	 * @param fansAttentionType
	 * @param fansattention
	 * @param userWapper
	 * @throws Exception
	 */
	private void saveFansattention(String username, FansAttentionType fansAttentionType, Fansattention fansattention, UserWapper userWapper) throws Exception {
		// TODO Auto-generated method stub

		for (User user : userWapper.getUsers()) {
			//设置信息
			fansattention = BaseController.setFansattention(user, username, fansAttentionType.getCode());
			//保存粉丝信息
			fansAttentionService.saveFansattention(fansattention);
		}
	}
}
